package com.yami.shop.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.app.dto.*;
import com.yami.shop.bean.app.vo.ProductVO;
import com.yami.shop.bean.enums.ProdStatusEnums;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.event.CheckAddrEvent;
import com.yami.shop.bean.event.LoadProdActivistEvent;
import com.yami.shop.bean.event.ProcessActivityProdPriceEvent;
import com.yami.shop.bean.event.ProdRightsEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.EsProductParam;
import com.yami.shop.bean.param.ProductParam;
import com.yami.shop.bean.vo.search.*;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.*;
import com.yami.shop.delivery.common.model.SameCity;
import com.yami.shop.delivery.common.service.SameCityService;
import com.yami.shop.mystery.common.dto.ActivityPresellDto;
import com.yami.shop.mystery.common.dto.ActivityProdDataDto;
import com.yami.shop.mystery.common.model.ActivitySubject;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.ActivityProdService;
import com.yami.shop.mystery.common.service.ActivitySubjectService;
import com.yami.shop.rights.common.model.ProdRights;
import com.yami.shop.rights.common.service.ProdRightsService;
import com.yami.shop.search.common.param.EsPageParam;
import com.yami.shop.search.common.service.SearchProductService;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author LGH
 */
@RestController
@RequestMapping("/prod")
@Tag(name = "商品接口")
@Log4j2
public class ProdController {

    @Autowired
    private ProductService prodService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SameCityService sameCityService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private SkuService skuService;
    @Autowired
    private ProdCommService prodCommService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ProdParameterService prodParameterService;
    @Autowired
    private SearchProductService searchProductService;
    @Autowired
    private ActivityPresellService activityPresellService;
    @Autowired
    private ActivitySubjectService activitySubjectService;
    @Autowired
    private ChannelUserRelationRecordService channelUserRelationRecordService;
    @Autowired
    private ProdNftService prodNftService;
    @Autowired
    private ProdRightsService prodRightsService;
    @Autowired
    private ActivityProdService activityProdService;


    @GetMapping("/prodInfo")
    @Operation(summary =  "商品详情信息", description = "根据商品ID（prodId）获取商品信息")
    @Parameter(name = "prodId", description = "商品ID", required = true)
    public ServerResponseEntity<ProductVO> prodInfo(Long prodId, String userId) {
        Product product = prodService.getProductInfo(prodId);
        if (product == null || product.getStatus() != 1) {
            // 商品已下线
            throw new YamiShopBindException("yami.product.off.shelves");
        }
        product.setProdLangList(null);
        // 检查店铺是否处于营业状态
        checkShopStatusIsOpen(product);
        // 启用的sku列表
        List<Sku> skuList = skuService.listPutOnSkuAndSkuStock(prodId);
        product.setSkuList(skuList);
        ProductVO productVO = BeanUtil.map(product, ProductVO.class);
        if(Objects.equals(productVO.getProdType(), ProdType.PROD_TYPE_ACTIVE.value()) || productVO.getMold() == 1){
            productVO.setIsDelivery(true);
        }else{
            // 判断用户默认地址是否在配送区域内
            applicationContext.publishEvent(new CheckAddrEvent(0L, userId, productVO, null));
        }
        // 如果是积分商品， 所有数据已经获取完成了
        if (Objects.equals(productVO.getProdType(), ProdType.PROD_TYPE_SCORE.value())) {
            return ServerResponseEntity.success(productVO);
        }
        // 发送事件，获取商品可用的正在开播直播间、商品套餐、秒杀、团购、积分商品信息
        applicationContext.publishEvent(new LoadProdActivistEvent(prodId, productVO, product.getProdType()));
        // 普通商品有多种物流，需要加载物流模板信息
//        if (Objects.equals(productVO.getProdType(), ProdType.PROD_TYPE_NORMAL.value())) {
        loadDeliveryMode(product.getDeliveryMode(), productVO);
//        }
        // 商品参数列表
        List<ProdParameter> prodParameters = prodParameterService.listParameterByProdId(prodId);
        productVO.setProdParameterList(prodParameters);
        return ServerResponseEntity.success(productVO);
    }

    @GetMapping("/skuList")
    @Operation(summary =  "sku信息", description = "根据商品ID（prodId）单独获取sku信息")
    @Parameter(name = "prodId", description = "商品ID", required = true)
    public ServerResponseEntity<List<SkuDto>> skuList(@RequestParam("prodId") Long prodId) {
        return ServerResponseEntity.success(skuService.getProdDetailSkuInfo(prodId));
    }

    @GetMapping("/isStatus")
    @Operation(summary =  "校验商品是否下架", description = "根据商品ID（prodId）校验商品是否下架")
    @Parameter(name = "prodId", description = "商品ID", required = true)
    public ServerResponseEntity<Boolean> isStatus(Long prodId) {
        Product product = prodService.getProductByProdId(prodId);
        if (product == null || product.getStatus() != 1) {
            return ServerResponseEntity.success(false);
        }
        return ServerResponseEntity.success(true);
    }

    @GetMapping("/listProdByIdsAndType")
    @Operation(summary =  "获取商品信息", description = "根据商品ids获取商品信息")
    public ServerResponseEntity<List<ProductDto>> listProdByIdsAndType(@ParameterObject ApiProdDto apiProdDto) {
        ProductParam productParam = BeanUtil.map(apiProdDto, ProductParam.class);
        apiProdDto.setLang(I18nMessage.getDbLang());
        apiProdDto.setStatus(ProdStatusEnums.NORMAL.getValue());
        List<Product> products = prodService.listProdByIdsAndType(productParam);
        processActivityProdPrice(productParam, products);
        List<ProductDto> productDtos = BeanUtil.mapAsList(products, ProductDto.class);
        return ServerResponseEntity.success(productDtos);
    }

    /**
     * 处理下活动商品的价格
     *
     * @param product  筛选参数
     * @param products 商品列表
     */
    private void processActivityProdPrice(ProductParam product, List<Product> products) {
        Map<Integer, List<Product>> prodMap = products.stream().collect(Collectors.groupingBy(Product::getProdType));
        if (prodMap.containsKey(ProdType.PROD_TYPE_SECKILL.value())) {
            applicationContext.publishEvent(new ProcessActivityProdPriceEvent(product, prodMap.get(ProdType.PROD_TYPE_SECKILL.value())));
        }

        if (prodMap.containsKey(ProdType.PROD_TYPE_GROUP.value())) {
            applicationContext.publishEvent(new ProcessActivityProdPriceEvent(product, prodMap.get(ProdType.PROD_TYPE_GROUP.value())));
        }
    }

    @GetMapping("/prodCommData")
    @Operation(summary =  "返回商品评论数据(好评率 好评数量 中评数 差评数)", description = "根据商品id获取")
    @Parameter(name = "prodId", description = "商品id", required = true)
    public ServerResponseEntity<ProdCommDataDto> getProdCommData(Long prodId) {
        return ServerResponseEntity.success(prodCommService.getProdCommDataByProdId(prodId));
    }

    @GetMapping("/prodCommPageByProd")
    @Operation(summary =  "根据商品返回评论分页数据", description = "传入商品id和页码")
    @Parameters({
            @Parameter(name = "prodId", description = "商品id", required = true),
            @Parameter(name = "evaluate", description = "-1或null 全部，0好评 1中评 2差评 3有图", required = true),
    })
    public ServerResponseEntity<IPage<ProdCommDto>> getProdCommPageByProdId(PageParam page, Long prodId, Integer evaluate) {
        return ServerResponseEntity.success(prodCommService.getProdCommDtoPageByProdId(page, prodId, evaluate));
    }

    /**
     *  用户未登录情况下的商品推荐
     * @param page
     * @param productParam
     * @return
     */
    @GetMapping("/recommendList")
    @Operation(summary =  "推荐商品列表", description = "根据商品ID（prodId）获取商品信息")
    public ServerResponseEntity<EsPageVO<EsProductSearchVO>> recommendList(PageParam page, @ParameterObject ProductParam productParam) {
        EsProductParam esProductParam = new EsProductParam();
        if (Objects.isNull(productParam.getProdType())) {
            esProductParam.setProdType(ProdType.PROD_TYPE_NORMAL.value());
        }
        Long primaryCategoryId = null;
        List<Category> categoryList = categoryService.getCategoryAndParent(productParam.getCategoryId());
        if (CollUtil.isNotEmpty(categoryList)) {
            primaryCategoryId = categoryList.get(0).getCategoryId();
        }
        esProductParam.setPrimaryCategoryId(primaryCategoryId);
        //如果有商品id则过滤掉
        if (Objects.nonNull(productParam.getProdId())) {
            List<Long> prodIds = new ArrayList<>();
            prodIds.add(productParam.getProdId());
            esProductParam.setSpuIdsExclude(prodIds);
        }
        EsPageParam esPageParam = new EsPageParam();
        esPageParam.setCurrent((int) page.getCurrent());
        esPageParam.setSize((int) page.getSize());
        EsPageVO<EsProductSearchVO> productPage = searchProductService.page(esPageParam, esProductParam, Boolean.FALSE);
        List<ProductSearchVO> products = productPage.getRecords().get(0).getProducts();
        long current = page.getCurrent();
        long size = page.getSize();
        int spuNum = products.size();
        // 推荐商品的数量不足时，查询额外的商品进行填充
        if (Objects.equals(current , 1L) && size > spuNum) {
            esPageParam.setSize(Math.toIntExact(size - spuNum));
            esPageParam.setCurrent(1);
            // 查询该分类以外的商品
            esProductParam.setPrimaryCategoryId(null);
            esProductParam.setNotPrimaryCategoryId(primaryCategoryId);
            EsPageVO<EsProductSearchVO> subProductPage = searchProductService.page(esPageParam, esProductParam, Boolean.FALSE);
            for (EsProductSearchVO productSearchVO : subProductPage.getRecords()) {
                if (CollUtil.isNotEmpty(productSearchVO.getProducts())) {
                    products.addAll(productSearchVO.getProducts());
                }
            }
            productPage.setTotal((long) products.size());
            productPage.setPages(productPage.getTotal() > 0 ? (int)page.getCurrent() : 0);
        }
        return ServerResponseEntity.success(productPage);
    }


    /**
     * 功能描述: 未登录下 微发行商品列表
     * @Author: LSR
     * @Date: 2023/4/19 18:50
     */
    @GetMapping("/microreleaseList")
    @Operation(summary =  "微发行商品列表", description = "微发行商品列表")
    public ServerResponseEntity<EsPageVO<MicroreleaseProductSearchVo>> microreleaseList(PageParam page, @ParameterObject EsProductParam productParam) {
//        if(ObjectUtil.isEmpty(productParam.getShopId())){
//            return ServerResponseEntity.success();
//        }
        // 获取开启活动的活动ID
        List<ActivityPresellDto> activityPresellDtos = activityPresellService.selectAllActivityPresellByActivityTypes(Arrays.asList(1L, 3L));
        // 根据ID转化为Map
        Map<Long, ActivityPresellDto> activityPresellMap = activityPresellDtos.stream().collect(Collectors.toMap(ActivityPresellDto::getId, Function.identity()));

        List<Long> activityIds = activityPresellDtos.stream().map(ActivityPresellDto::getId).collect(Collectors.toList());
        productParam.setActivityIds(activityIds);
        EsPageParam esPageParam = new EsPageParam();
        esPageParam.setCurrent((int) page.getCurrent());
        esPageParam.setSize((int) page.getSize());
        EsPageVO<MicroreleaseProductSearchVo> productPage = searchProductService.microreleasePage(esPageParam, productParam, Boolean.FALSE);
        // 循环组装数据
        for (MicroreleaseProductSearchVo microreleaseProductSearchVo : productPage.getRecords()) {
            // 没有活动获取商品默认限购数
            microreleaseProductSearchVo.setRuleMaxNum(microreleaseProductSearchVo.getMaxNum());
            if (microreleaseProductSearchVo.getActivityId() != 0) {
                ActivityPresellDto activityPresellDto = activityPresellMap.get(microreleaseProductSearchVo.getActivityId());
                if (ObjectUtil.isNotEmpty(activityPresellDto)) {
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getMaxNum()) && activityPresellDto.getMaxNum() > 0){
                        microreleaseProductSearchVo.setMaxNum(activityPresellDto.getMaxNum());
                    }
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getRuleMaxNum()) && activityPresellDto.getRuleMaxNum() > 0){
                        microreleaseProductSearchVo.setRuleMaxNum(activityPresellDto.getRuleMaxNum());
                    }
                    microreleaseProductSearchVo.setStartTime(activityPresellDto.getPutawayTime());
                }
            }
        }
        return ServerResponseEntity.success(productPage);
    }


    @GetMapping("/microreleaseListByActivitySubjectId")
    @Operation(summary =  "微发行零元购商品列表通过活动专题ID查询", description = "微发行零元购商品列表通过活动专题ID查询")
    public ServerResponseEntity<PageVO<MicroreleaseProductSearchVo>> microreleaseListByActivitySubjectId(PageDTO page, @ParameterObject EsProductParam productParam) {
        if(ObjectUtil.isEmpty(productParam.getActivitySubjectId())){
            return ServerResponseEntity.success();
        }
        // 获取活动
        ActivitySubject byId = activitySubjectService.getById(productParam.getActivitySubjectId());
        if(ObjectUtils.isEmpty(byId)){
            return ServerResponseEntity.success();
        }
        // 获取开启活动的活动ID
        PageVO<MicroreleaseProductSearchVo> pageVO = activityPresellService.selectPageActivityPresellByActivityIds(page,Arrays.asList(byId.getActivityId().split(",")), Arrays.asList(1L, 3L));
        if(ObjectUtils.isEmpty(pageVO.getList())){
            return ServerResponseEntity.success();
        }
        // 获取 商品信息
        List<Long> prodIds = pageVO.getList().stream().map(MicroreleaseProductSearchVo::getProdId).collect(Collectors.toList());
        productParam.setProdIds(prodIds);
//        productParam.setAppDisplay(false);
        EsPageParam esPageParam = new EsPageParam();
        esPageParam.setCurrent(1);
        esPageParam.setSize(prodIds.size());
        EsPageVO<MicroreleaseProductSearchVo> productPage = searchProductService.microreleasePage(esPageParam, productParam, Boolean.FALSE);
        Map<Long, MicroreleaseProductSearchVo> prodMap = productPage.getRecords().stream().collect(Collectors.toMap(MicroreleaseProductSearchVo::getProdId, u -> u, (key1, key2) -> key1));

        // 循环组装数据
        for (MicroreleaseProductSearchVo microreleaseProductSearchVo : pageVO.getList()) {
            // 获取商品信息
            MicroreleaseProductSearchVo prodVo = prodMap.get(microreleaseProductSearchVo.getProdId());
            BeanUtils.copyProperties(prodVo,microreleaseProductSearchVo,"activityId","price","ruleMaxNum","startTime","endTime");
            if(ObjectUtil.isEmpty(microreleaseProductSearchVo.getRuleMaxNum())){
                microreleaseProductSearchVo.setRuleMaxNum(prodVo.getRuleMaxNum());
            }
            if(ObjectUtil.isEmpty(microreleaseProductSearchVo.getPrice()) || microreleaseProductSearchVo.getPrice() == 0){
                microreleaseProductSearchVo.setPrice(prodVo.getPrice());
            }else{
                BigDecimal divide = BigDecimal.valueOf(microreleaseProductSearchVo.getPrice()).divide(new BigDecimal(100));
                microreleaseProductSearchVo.setPrice(divide.doubleValue());
            }
            if(new Date().compareTo(microreleaseProductSearchVo.getStartTime()) < 0){
                microreleaseProductSearchVo.setStatus(9);
            }
        }
        return ServerResponseEntity.success(pageVO);
    }


//
//    @GetMapping("/microreleaseList")
//    @Operation(summary =  "微发行零元购商品列表通过活动专题ID查询", description = "微发行零元购商品列表通过活动专题ID查询")
//    public ServerResponseEntity<PageVO<MicroreleaseProductSearchVo>> microreleaseList(PageDTO page, @ParameterObject EsProductParam productParam) {
//        // 获取活动
//        List<ActivitySubject> list = activitySubjectService.list();
//        if(CollectionUtils.isEmpty(list)){
//            return ServerResponseEntity.success();
//        }
//        List<String> ids = list.stream().map(ActivitySubject::getActivityId).collect(Collectors.toList());
//        // 获取开启活动的活动ID
//        PageVO<MicroreleaseProductSearchVo> pageVO = activityPresellService.selectPageActivityPresellByActivityIds(page,ids, Arrays.asList(1L, 3L));
//        if(ObjectUtils.isEmpty(pageVO.getList())){
//            return ServerResponseEntity.success();
//        }
//        // 获取 商品信息
//        List<Long> prodIds = pageVO.getList().stream().map(MicroreleaseProductSearchVo::getProdId).collect(Collectors.toList());
//        productParam.setProdIds(prodIds);
////        productParam.setAppDisplay(false);
//        EsPageParam esPageParam = new EsPageParam();
//        esPageParam.setCurrent(1);
//        esPageParam.setSize(prodIds.size());
//        EsPageVO<MicroreleaseProductSearchVo> productPage = searchProductService.microreleasePage(esPageParam, productParam, Boolean.FALSE);
//        Map<Long, MicroreleaseProductSearchVo> prodMap = productPage.getRecords().stream().collect(Collectors.toMap(MicroreleaseProductSearchVo::getProdId, u -> u, (key1, key2) -> key1));
//
//        // 循环组装数据
//        for (MicroreleaseProductSearchVo microreleaseProductSearchVo : pageVO.getList()) {
//            // 获取商品信息
//            MicroreleaseProductSearchVo prodVo = prodMap.get(microreleaseProductSearchVo.getProdId());
//            BeanUtils.copyProperties(prodVo,microreleaseProductSearchVo,"activityId","price","ruleMaxNum","startTime","endTime");
//            if(ObjectUtil.isEmpty(microreleaseProductSearchVo.getRuleMaxNum())){
//                microreleaseProductSearchVo.setRuleMaxNum(prodVo.getRuleMaxNum());
//            }
//            if(ObjectUtil.isEmpty(microreleaseProductSearchVo.getPrice()) || microreleaseProductSearchVo.getPrice() == 0){
//                microreleaseProductSearchVo.setPrice(prodVo.getPrice());
//            }else{
//                BigDecimal divide = BigDecimal.valueOf(microreleaseProductSearchVo.getPrice()).divide(new BigDecimal(100));
//                microreleaseProductSearchVo.setPrice(divide.doubleValue());
//            }
//            if(new Date().compareTo(microreleaseProductSearchVo.getStartTime()) < 0){
//                microreleaseProductSearchVo.setStatus(9);
//            }
//        }
//        return ServerResponseEntity.success(pageVO);
//    }



    @GetMapping("/microreleaseListByActivitySubjectIds")
    @Operation(summary =  "微发行零元购商品列表通过活动专题ID查询", description = "微发行零元购商品列表通过活动专题ID查询")
    public ServerResponseEntity<List<MicroreleaseProductListVO>> microreleaseListByActivitySubjectIds(PageDTO page, @ParameterObject EsProductParam productParam) {
        if(StringUtils.isEmpty(productParam.getActivitySubjectIds())){
            return ServerResponseEntity.success();
        }
        List<MicroreleaseProductListVO> microreleaseProductListVOs = new ArrayList<>();
        List<Long> activitySubjectIds = Arrays.stream(productParam.getActivitySubjectIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        for (Long activitySubjectId : activitySubjectIds) {
            MicroreleaseProductListVO microreleaseProduct = new MicroreleaseProductListVO();
            // 获取活动
            ActivitySubject byId = activitySubjectService.getById(activitySubjectId);
            microreleaseProduct.setName(byId.getName());
            microreleaseProduct.setImgs(byId.getImgs());
            microreleaseProduct.setContent(byId.getContent());
            if(ObjectUtils.isEmpty(byId)){
                return ServerResponseEntity.success();
            }
            // 获取开启活动的活动ID
            PageVO<MicroreleaseProductSearchVo> pageVO = activityPresellService.selectPageActivityPresellByActivityIds(page,Arrays.asList(byId.getActivityId().split(",")), Arrays.asList(1L, 3L));
            if(ObjectUtils.isEmpty(pageVO.getList())){
                return ServerResponseEntity.success();
            }
            // 获取 商品信息
            List<Long> prodIds = pageVO.getList().stream().map(MicroreleaseProductSearchVo::getProdId).collect(Collectors.toList());
            productParam.setProdIds(prodIds);
//        productParam.setAppDisplay(false);
            EsPageParam esPageParam = new EsPageParam();
            esPageParam.setCurrent(1);
            esPageParam.setSize(prodIds.size());
            EsPageVO<MicroreleaseProductSearchVo> productPage = searchProductService.microreleasePage(esPageParam, productParam, Boolean.FALSE);
            Map<Long, MicroreleaseProductSearchVo> prodMap = productPage.getRecords().stream().collect(Collectors.toMap(MicroreleaseProductSearchVo::getProdId, u -> u, (key1, key2) -> key1));

            // 循环组装数据
            for (MicroreleaseProductSearchVo microreleaseProductSearchVo : pageVO.getList()) {
                // 获取商品信息
                MicroreleaseProductSearchVo prodVo = prodMap.get(microreleaseProductSearchVo.getProdId());
                BeanUtils.copyProperties(prodVo,microreleaseProductSearchVo,"activityId","price","ruleMaxNum","startTime","endTime");
                if(ObjectUtil.isEmpty(microreleaseProductSearchVo.getRuleMaxNum())){
                    microreleaseProductSearchVo.setRuleMaxNum(prodVo.getRuleMaxNum());
                }
                if(ObjectUtil.isEmpty(microreleaseProductSearchVo.getPrice()) || microreleaseProductSearchVo.getPrice() == 0){
                    microreleaseProductSearchVo.setPrice(prodVo.getPrice());
                }else{
                    BigDecimal divide = BigDecimal.valueOf(microreleaseProductSearchVo.getPrice()).divide(new BigDecimal(100));
                    microreleaseProductSearchVo.setPrice(divide.doubleValue());
                }
                if(new Date().compareTo(microreleaseProductSearchVo.getStartTime()) < 0){
                    microreleaseProductSearchVo.setStatus(9);
                }
            }
            microreleaseProduct.setProducts(productPage);
            microreleaseProductListVOs.add(microreleaseProduct);
        }
        return ServerResponseEntity.success(microreleaseProductListVOs);
    }

    @GetMapping("/getProdRightsByProdId")
    @Operation(summary =  "通过商品id获取权益列表", description = "根据商品ID（prodId）获取商品信息")
    public ServerResponseEntity<List<ProdRights>> getProdRightsByProdId(Long prodId) {
        ProdNft dataByProdId = prodNftService.getDataByProdId(prodId);
        List<ProdRights> list = Lists.newArrayList();
        if(ObjectUtil.isNotEmpty(dataByProdId.getRightsId())){
            // 获取权益信息
            QueryWrapper<ProdRights> prodRightsQueryWrapper = new QueryWrapper<>();
            prodRightsQueryWrapper.ne("status",-1);
            prodRightsQueryWrapper.in("id",Arrays.asList(dataByProdId.getRightsId().split(",")));
            list = prodRightsService.list(prodRightsQueryWrapper);
        }
        return ServerResponseEntity.success(list);
    }
    @GetMapping("/getProdInfo")
    @Operation(summary =  "获取商品信息", description = "根据商品ID（prodId）获取商品信息")
    public ServerResponseEntity<MicroreleaseProductSearchVo> recommend(Long prodId,String userId,Long activityId) {
        MicroreleaseProductSearchVo productSearchVO = new MicroreleaseProductSearchVo();
        Product product = prodService.getProductInfo(prodId);
        if (product == null || product.getStatus() == -1 || product.getStatus() == 0) {
            // 商品已下线
            throw new YamiShopBindException("yami.product.off.shelves");
        }
        cn.hutool.core.bean.BeanUtil.copyProperties(product, productSearchVO);

        // 获取虚拟商品
        if (product.getMold() == 2 || product.getMold() == 4) {
            ProdNft dataByProdId = prodNftService.getDataByProdId(prodId);
            cn.hutool.core.bean.BeanUtil.copyProperties(dataByProdId, productSearchVO, "chain");
            productSearchVO.setIsRights(ObjectUtil.isNotEmpty(dataByProdId.getRightsId()) ? 1 : 0);
            if(ObjectUtil.isNotEmpty(dataByProdId.getRightsId())){
                // 获取权益信息
                QueryWrapper<ProdRights> prodRightsQueryWrapper = new QueryWrapper<>();
                prodRightsQueryWrapper.ne("status",-1);
                prodRightsQueryWrapper.in("id",Arrays.asList(dataByProdId.getRightsId().split(",")));
                List<ProdRights> list = prodRightsService.list(prodRightsQueryWrapper);
                productSearchVO.setProdRights(cn.hutool.core.bean.BeanUtil.copyToList(list, ProdRightSearchVO.class));
            }
        }
        if (ObjectUtil.isNotEmpty(userId)) {
            // 该用户是否绑定链
            Boolean hasDTCAddress = channelUserRelationRecordService.isHasDTCAddress(userId, product.getChain(), product.getChannelCode());
            productSearchVO.setIsHasDTCAddress(hasDTCAddress);
            productSearchVO.setChainCode(product.getChain());

            if(product.getProdType() == 6){
                // 获取活动信息
                productSearchVO.setActivityId(activityId);
                ProdRightsEvent prodRightsEvent = new ProdRightsEvent();
                prodRightsEvent.setProductSearchVO(productSearchVO);
                prodRightsEvent.setUserId(userId);
                applicationContext.publishEvent(prodRightsEvent);
            }
        }
//        else {
//            // 通过商品ID查活动信息
//            List<ActivityPresellDto> activityPresellDtos = activityPresellService.selectAllActivityPresellByProdId(prodId);
//            if(ObjectUtil.isNotEmpty(activityPresellDtos)){
//                ActivityPresellDto activityPresellDto = activityPresellDtos.get(0);
//                if(ObjectUtil.isNotEmpty(activityPresellDto)){
//                    productSearchVO.setStartTime(activityPresellDto.getPutawayTime());
//                    productSearchVO.setRuleMaxNum(activityPresellDto.getRuleMaxNum());
//                }
//            }
//        }
        // 通过活动ID以及商品ID获取活动信息
        ActivityProdDataDto activityPresell = activityPresellService.getDataByActivityAndProdId(activityId,prodId);
        if(ObjectUtil.isNotEmpty(activityPresell)){
            productSearchVO.setStartTime(activityPresell.getActivityStartTime());
            if(new Date().compareTo(activityPresell.getActivityStartTime()) < 0){
                productSearchVO.setStatus(9);
                productSearchVO.setIsPurchase(0);
            }
            productSearchVO.setTotalStocks(activityPresell.getProdTotalStocks());
            productSearchVO.setRuleMaxNum(activityPresell.getPurchaseNum());
            productSearchVO.setMaxNum(activityPresell.getPurchaseNum());
            BigDecimal divide = BigDecimal.valueOf(activityPresell.getPreemptionPrice()).divide(new BigDecimal(100));
            productSearchVO.setPrice(divide.doubleValue());
        }

//        productSearchVO.setChain(product.getChain());
        return ServerResponseEntity.success(productSearchVO);
    }

    private void checkShopStatusIsOpen(Product product) {
        // 积分商品的平台店铺不需要检验
        if (Objects.equals(product.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            return;
        }
        Date now = new Date();
        ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(product.getShopId());
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OPEN.value())) {
            return;
        }
        product.setShopName(shopDetail.getShopName());
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value()) || Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE_AUDIT.value())) {
            throw new YamiShopBindException("yami.store.offline");
        }
        if (Objects.equals(shopDetail.getShopStatus(), ShopStatus.STOP.value())) {
            if (now.compareTo(shopDetail.getContractStartTime()) < 0) {
                throw new YamiShopBindException("yami.store.not.open");
            } else {
                throw new YamiShopBindException("yami.store.stop.open");
            }
        }
        throw new YamiShopBindException("yami.store.status.error");
    }

    /**
     * 加载商品物流模板
     * @param deliveryMode
     * @param productVO
     */
    private void loadDeliveryMode(String deliveryMode, ProductVO productVO) {
        // 物流模板
        Product.DeliveryModeVO deliveryModeVO = Json.parseObject(deliveryMode, Product.DeliveryModeVO.class);
        SameCity sameCity = sameCityService.getSameCityByShopId(productVO.getShopId());
        // 如果同城配送是关闭了的，前端就不需要显示同城配送了
        if (Objects.isNull(sameCity) || !Objects.equals(1, sameCity.getStatus()) || Objects.isNull(deliveryModeVO.getHasCityDelivery())) {
            deliveryModeVO.setHasCityDelivery(false);
        }
        if (deliveryModeVO.getHasCityDelivery() != null && deliveryModeVO.getHasCityDelivery() && Objects.nonNull(sameCity)) {
            productVO.setStartDeliveryFee(sameCity.getStartingFee());
        }
        productVO.setDeliveryModeVO(deliveryModeVO);
    }
}
